package com.learn.kotlinlearndemolist.listview

import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.RecyclerView
import com.learn.kotlinlearndemolist.model.Fruit
import com.learn.kotlinlearndemolist.R
import com.learn.kotlinlearndemolist.databinding.ListItemBinding

class FruitRecAdapter(val fruitList: MutableList<Fruit>) :
    RecyclerView.Adapter<FruitRecAdapter.ViewHolder>() {
    private lateinit var mBinding: ListItemBinding

    class ViewHolder(itemBinding: ListItemBinding) : RecyclerView.ViewHolder(itemBinding.root) {
        private val mBinding = itemBinding
        fun binding(fruit: Fruit) {
            mBinding.fruitImg.setImageResource(fruit.id)
            mBinding.fruitName.text = fruit.name
            mBinding.fruitName.setOnClickListener {
                Toast.makeText(mBinding.root.context, fruit.name, Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FruitRecAdapter.ViewHolder {
        mBinding = DataBindingUtil.inflate(
            LayoutInflater.from(parent.context),
            R.layout.list_item,
            parent,
            false
        )
        return ViewHolder(mBinding)
    }

    override fun onBindViewHolder(holder: FruitRecAdapter.ViewHolder, position: Int) {
        holder.binding(fruitList[position])
    }

    override fun getItemCount() = fruitList.size
}